/*
 * @Description: 企业列表页面
 * @Autor: lizhengkun
 * @Date: 2021-08-12 16:26:12
 * @LastEditTime: 2021-08-12 18:16:25
 */
import React, { useState } from 'react';
import styles from './index.module.less';
import ApproveCard from '@/components/card';
import { getEnterpriseList, switchUserEnterprise } from '@/services/enterprise';
import { SwipeAction, Toast, Modal } from 'antd-mobile-v2';
import FilterArea, { OptionsListItem } from '@/components/filter-area';
import { SecondConfirm } from '@/components/second-confirm';
import { DRAFT_QUERY_TYPE } from '../../official-doc/constants';
import AntdRefreshList from '@/components/antd-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import EmptyLoading from '@/components/empty/empty-loading';
import { Prompt } from 'react-router-dom';
import { PrintNum } from '@/utils';
import { useRefreshList } from '@/hooks/use-refresh-list';
import { SetToken, ClearUserInfo } from '@/utils/session';
import { store } from '@/redux';
import { useSelector } from 'react-redux';

const alert = Modal.alert;

const filterData: OptionsListItem[] = [
  {
    label: '类型',
    value: 'type',
    options: [
      { label: '全部', value: '' },
      {
        label: '申报',
        value: `${DRAFT_QUERY_TYPE.DECLARE_STUDENT},${DRAFT_QUERY_TYPE.DECLARE_OUTSCHOOL},${DRAFT_QUERY_TYPE.DECLARE_INOTHER}`
      }
    ]
  },
  {
    label: '时间',
    value: 'time',
    options: [
      { label: '全部', value: '' },
      { label: '近3天', value: 3 },
      { label: '近7天', value: 7 },
      { label: '近30天', value: 30 }
    ]
  }
];

interface EnterpriseItem {
  tenantId: string;
  id?: string;
}

const height =
  document.documentElement.clientHeight -
  (document.documentElement.clientWidth * 11) / 100;

const EnterpriseList: React.FC<RouterProps> = (props) => {
  const defaultPageSize = 10;
  const dispath = store.dispatch;

  const { userInfo } = useSelector((state: any) => ({
    userInfo: state.common.userInfo
  }));
  // console.log('userInfo:', userInfo);

  let timer = null;
  const [pageSize, setPageSize] = useState(defaultPageSize);

  // todo?  后续可能改成分页形式
  const {
    showDom,
    refreshing,
    loadingMore,
    dataSource,
    searchData,
    setDatasource,
    handleRefresh,
    handleLoadMore,
    handleSearch,
    routeWillLeave
  } = useRefreshList({
    routeProps: props,
    cacheRouteList: ['/enterprise/list'],
    pullData: async (options) => {
      const res = await getEnterpriseList();
      const list = formatData(res.data || []) || [];
      setDatasource(list);
      // setSurplusTotal(surplusTotal < 0 ? 0 : surplusTotal);
      // setPageSize(
      //   params?.pageNum
      //     ? PrintNum(params?.pageNum * defaultPageSize)
      //     : defaultPageSize
      // );
      // setData(params?.lastId ? dataSource.concat(list) : list);
      // setLastId(list[list.length - 1]?.id);
    }
  });

  const formatData = (data: any[]): any => {
    data?.forEach((item) => {
      item.formData = [
        // { label: '企业名称', value: item.tenantName || '无' },
        // {
        //   label: '部门名称',
        //   value: item.orgName || '无',
        // },
        // {
        //   label: '用户名称',
        //   value: item.userName || '无',
        // },
      ];
      item.cardTitle = item.tenantName || '无';
      item.crtUserName = item.userName;
    });
    return data;
  };

  const handleCardClick = (item: EnterpriseItem) => {
    alert('切换', '确认切换企业？', [
      { text: '取消' },
      { text: '确定', onPress: () => handleSwitchEnterprise(item) }
    ]);
  };

  const handleSwitchEnterprise = async (item: { tenantId: string }) => {
    const res: any = await switchUserEnterprise({ tenantId: item.tenantId });
    if (res.status === 200) {
      const token = res.data;
      ClearUserInfo();
      SetToken(token);
      Toast.success('切换成功');
      dispath({
        type: 'common/getUserInfo',
        payload: null
      });
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        // 页面跳转会请求userInfo
        props.history.push('/personal-center');
      }, 10);
    } else {
      Toast.success(res?.message || '切换失败');
    }
  };

  const rightBtns = (itemInfo: { tenantId: string; id: number }) => {
    return [
      // {
      //   text: '切换企业',
      //   style: {
      //     backgroundColor: '#C7C7CC',
      //     color: 'white',
      //     fontSize: '18px',
      //     padding: '7px',
      //   },
      //   onPress: () => {
      //     const params = {
      //       buttons: [
      //         {
      //           text: '确定',
      //           cb: () => handleSwitchEnterprise(itemInfo),
      //         },
      //         {
      //           text: '取消',
      //         },
      //       ],
      //       message: '确认切换企业？',
      //     };
      //     SecondConfirm(params);
      //   },
      // },
    ].filter((item) => item);
  };

  return (
    <div>
      {/* <FilterArea
        data={filterData}
        values={searchData}
        onFilterChange={handleSearch}
      /> */}
      <div className={styles.pageHeader}>企业列表</div>
      {showDom ? (
        <div className={styles.cardList}>
          {dataSource?.length > 0 ? (
            <AntdRefreshList
              height={height}
              initialListSize={pageSize}
              dataSource={dataSource}
              refreshing={refreshing}
              loadingMore={loadingMore}
              renderRow={(item, sectionID, index) => (
                <div className={styles.cardItem} key={index}>
                  <SwipeAction right={rightBtns(item)}>
                    <div
                      onClick={() => handleCardClick(item)}
                      className={
                        item.curTenant === true ? styles.cardActive : ''
                      }
                    >
                      <ApproveCard data={item} hasAvatar></ApproveCard>
                    </div>
                  </SwipeAction>
                </div>
              )}
              onRefresh={handleRefresh}
              onEndReached={handleLoadMore}
            />
          ) : (
            <EmptyRefresh
              refreshing={refreshing}
              onRefresh={handleRefresh}
              emptyProps={{ text: '暂无数据' }}
            />
          )}
        </div>
      ) : (
        <EmptyLoading />
      )}
      <Prompt message={routeWillLeave} />
    </div>
  );
};

export default EnterpriseList;
